// ============================================================================
// 账号页面对象模型
// ============================================================================

import { Page, Locator, expect } from '@playwright/test'
import { waitForPageLoad, safeClick, safeFill, waitForVisible, verifyNotification } from '../utils/test-utils'

export class AccountsPage {
  readonly page: Page
  
  // 页面元素
  readonly pageTitle: Locator
  readonly pageDescription: Locator
  readonly addAccountButton: Locator
  readonly accountCards: Locator
  readonly emptyState: Locator
  readonly loadingState: Locator
  readonly errorState: Locator
  readonly reloadButton: Locator
  
  // 账号卡片元素
  readonly accountNickname: Locator
  readonly accountUID: Locator
  readonly accountStatus: Locator
  readonly accountVipBadge: Locator
  readonly accountStats: Locator
  readonly deleteAccountButton: Locator
  readonly validateAccountButton: Locator
  
  // 添加账号模态框
  readonly addAccountModal: Locator
  readonly cookiesInput: Locator
  readonly submitButton: Locator
  readonly cancelButton: Locator

  constructor(page: Page) {
    this.page = page
    
    // 页面元素
    this.pageTitle = page.getByRole('heading', { name: '账号列表' })
    this.pageDescription = page.getByText(/管理您的微博登录账号/)
    this.addAccountButton = page.getByRole('button', { name: '添加账号' })
    this.accountCards = page.locator('[data-testid="account-card"]')
    this.emptyState = page.getByText('暂无账号')
    this.loadingState = page.getByText('加载数据中...')
    this.errorState = page.getByText('加载失败')
    this.reloadButton = page.getByRole('button', { name: '重新加载' })
    
    // 账号卡片元素
    this.accountNickname = page.locator('[data-testid="account-nickname"]')
    this.accountUID = page.locator('[data-testid="account-uid"]')
    this.accountStatus = page.locator('[data-testid="account-status"]')
    this.accountVipBadge = page.locator('[data-testid="account-vip-badge"]')
    this.accountStats = page.locator('[data-testid="account-stats"]')
    this.deleteAccountButton = page.locator('[data-testid="delete-account-button"]')
    this.validateAccountButton = page.locator('[data-testid="validate-account-button"]')
    
    // 添加账号模态框
    this.addAccountModal = page.locator('[data-testid="add-account-modal"]')
    this.cookiesInput = page.locator('[data-testid="cookies-input"]')
    this.submitButton = page.getByRole('button', { name: '确认添加' })
    this.cancelButton = page.getByRole('button', { name: '取消' })
  }

  /**
   * 导航到账号页面
   */
  async goto() {
    await this.page.goto('/accounts')
    await waitForPageLoad(this.page)
  }

  /**
   * 等待页面加载完成
   */
  async waitForLoad() {
    await waitForVisible(this.pageTitle)
    await waitForVisible(this.pageDescription)
  }

  /**
   * 验证页面标题和描述
   */
  async verifyPageHeader() {
    await expect(this.pageTitle).toBeVisible()
    await expect(this.pageDescription).toBeVisible()
    await expect(this.addAccountButton).toBeVisible()
  }

  /**
   * 获取账号卡片数量
   */
  async getAccountCount(): Promise<number> {
    return await this.accountCards.count()
  }

  /**
   * 验证账号卡片信息
   */
  async verifyAccountCard(index: number, expectedData: {
    nickname: string
    uid: string
    status: 'valid' | 'invalid'
    isVip?: boolean
    stats?: {
      followers: string
      following: string
      posts: string
    }
  }) {
    const card = this.accountCards.nth(index)
    await expect(card).toBeVisible()
    
    // 验证昵称
    const nickname = card.locator('[data-testid="account-nickname"]')
    await expect(nickname).toContainText(expectedData.nickname)
    
    // 验证UID
    const uid = card.locator('[data-testid="account-uid"]')
    await expect(uid).toContainText(expectedData.uid)
    
    // 验证状态
    const status = card.locator('[data-testid="account-status"]')
    const expectedStatusText = expectedData.status === 'valid' ? '有效' : '无效'
    await expect(status).toContainText(expectedStatusText)
    
    // 验证VIP标识
    if (expectedData.isVip) {
      const vipBadge = card.locator('[data-testid="account-vip-badge"]')
      await expect(vipBadge).toBeVisible()
    }
    
    // 验证统计信息
    if (expectedData.stats) {
      const stats = card.locator('[data-testid="account-stats"]')
      await expect(stats).toContainText(expectedData.stats.followers)
      await expect(stats).toContainText(expectedData.stats.following)
      await expect(stats).toContainText(expectedData.stats.posts)
    }
  }

  /**
   * 点击添加账号按钮
   */
  async clickAddAccount() {
    await safeClick(this.addAccountButton)
    await waitForVisible(this.addAccountModal)
  }

  /**
   * 填写账号信息并提交
   */
  async addAccount(cookies: string) {
    await this.clickAddAccount()
    await safeFill(this.cookiesInput, cookies)
    await safeClick(this.submitButton)
    
    // 等待模态框关闭
    await expect(this.addAccountModal).toBeHidden()
  }

  /**
   * 取消添加账号
   */
  async cancelAddAccount() {
    await safeClick(this.cancelButton)
    await expect(this.addAccountModal).toBeHidden()
  }

  /**
   * 删除指定账号
   */
  async deleteAccount(index: number, confirm: boolean = true) {
    const deleteButton = this.deleteAccountButton.nth(index)
    await safeClick(deleteButton)
    
    // 处理确认对话框
    this.page.on('dialog', async dialog => {
      if (confirm) {
        await dialog.accept()
      } else {
        await dialog.dismiss()
      }
    })
  }

  /**
   * 验证账号删除成功
   */
  async verifyAccountDeleted(originalCount: number) {
    const newCount = await this.getAccountCount()
    expect(newCount).toBe(originalCount - 1)
  }

  /**
   * 验证空状态
   */
  async verifyEmptyState() {
    await expect(this.emptyState).toBeVisible()
    await expect(this.accountCards).toHaveCount(0)
  }

  /**
   * 验证加载状态
   */
  async verifyLoadingState() {
    await expect(this.loadingState).toBeVisible()
  }

  /**
   * 验证错误状态
   */
  async verifyErrorState() {
    await expect(this.errorState).toBeVisible()
    await expect(this.reloadButton).toBeVisible()
  }

  /**
   * 点击重新加载
   */
  async clickReload() {
    await safeClick(this.reloadButton)
  }

  /**
   * 验证通知消息
   */
  async verifyNotification(message: string, type: 'success' | 'error' = 'success') {
    await verifyNotification(this.page, message, type)
  }

  /**
   * 搜索账号
   */
  async searchAccount(query: string) {
    const searchInput = this.page.locator('[data-testid="search-input"]')
    await safeFill(searchInput, query)
    
    // 等待搜索结果
    await this.page.waitForTimeout(500)
  }

  /**
   * 验证搜索结果
   */
  async verifySearchResults(expectedCount: number) {
    await expect(this.accountCards).toHaveCount(expectedCount)
  }

  /**
   * 验证账号状态更新
   */
  async verifyAccountStatusUpdate(index: number, expectedStatus: 'valid' | 'invalid') {
    const card = this.accountCards.nth(index)
    const status = card.locator('[data-testid="account-status"]')
    const expectedText = expectedStatus === 'valid' ? '有效' : '无效'
    
    await expect(status).toContainText(expectedText)
  }

  /**
   * 验证页面响应式设计
   */
  async verifyResponsiveDesign() {
    // 测试移动端布局
    await this.page.setViewportSize({ width: 375, height: 667 })
    await expect(this.pageTitle).toBeVisible()
    await expect(this.addAccountButton).toBeVisible()
    
    // 测试桌面端布局
    await this.page.setViewportSize({ width: 1280, height: 720 })
    await expect(this.pageTitle).toBeVisible()
    await expect(this.addAccountButton).toBeVisible()
  }

  /**
   * 验证键盘导航
   */
  async verifyKeyboardNavigation() {
    // 使用Tab键导航
    await this.page.keyboard.press('Tab')
    await expect(this.addAccountButton).toBeFocused()
    
    // 使用Enter键激活
    await this.page.keyboard.press('Enter')
    await waitForVisible(this.addAccountModal)
    
    // 使用Escape键关闭
    await this.page.keyboard.press('Escape')
    await expect(this.addAccountModal).toBeHidden()
  }
}
